package com.neusoft.neuiotms.dcam.workflow.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.activiti.dto.ProcessInstanceDTO;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetLifeCycleDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.service.AssetLifeCycleService;
import com.neusoft.neuiotms.dcam.fixed.service.AssetService;
import com.neusoft.neuiotms.dcam.workflow.converter.WeixiuSLConverter;
import com.neusoft.neuiotms.dcam.workflow.dto.ConfirmSLDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.WeixiuSLDTO;
import com.neusoft.neuiotms.dcam.workflow.model.WeixiuItemSL;
import com.neusoft.neuiotms.dcam.workflow.model.WeixiuSL;
import com.neusoft.neuiotms.dcam.workflow.repository.WeixiuItemSLRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.WeixiuSLRepository;
import com.neusoft.neuiotms.dcam.workflow.service.ConfirmSLService;
import com.neusoft.neuiotms.dcam.workflow.service.WeixiuSLService;

import io.micrometer.core.instrument.util.StringUtils;

@Service
public class WeixiuSLServiceImpl implements WeixiuSLService {

    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private WeixiuSLRepository weixiuSLRepository;
    @Autowired
    private WeixiuSLConverter weixiuSLConverter;
    @Autowired
    private WeixiuItemSLRepository weixiuItemSLRepository;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private AssetService assetService;
    @Autowired
    private AssetLifeCycleService assetLifeCycleService;
    @Autowired
    private ConfirmSLService confirmSLService;

    @Override
    @Transactional
    public WeixiuSLDTO create(final WeixiuSLDTO dto, final UserBean user) {

        final String taskId = dto.getTaskId();
        final ProcessInstanceDTO instance =
                this.workOrderService.submit(dto.getTitle(), DCAMConsts.PROCESSS_WEIXIU_SL_KEY, dto.getWorkOrderNum(),
                        user);
        dto.setTaskId(instance.getTaskId());
        dto.setWorkOrderNum(instance.getWorkorderNum());
        dto.setCreateUser(user.getUsername());
        dto.setCreateUserName(user.getName());

        // 查询当前workOrderNum和TaskId下是否存在记录
        final WeixiuSL oldModel = this.weixiuSLRepository.findByWorkOrderNumAndTaskId(
                dto.getWorkOrderNum(), taskId);
        if (oldModel == null) {
            dto.setId(null);
        }

        // 解锁以前的资产信息
        final List<WeixiuItemSL> all = this.weixiuItemSLRepository.findByMain_WorkOrderNum(dto.getWorkOrderNum());
        if (null != all) {
            this.assetService.updateLocked(all.stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                    false);
        }

        WeixiuSL model = this.weixiuSLConverter.toModel(dto);
        model = this.weixiuSLRepository.save(model);

        // 枷锁资产信息
        this.assetService.updateLocked(
                model.getDetails().stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                true);

        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);
        return this.weixiuSLConverter.toDTO(model);
    }

    @Override
    public WeixiuSLDTO detail(final String workOrderNum, final String taskId, final UserBean user) {
        WeixiuSL model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.weixiuSLRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new WeixiuSLDTO();
                    } else {
                        model = this.weixiuSLRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                model = this.weixiuSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.weixiuSLConverter.toDTO(model);
    }

    @Transactional
    @Override
    public void confirmCreate(final WeixiuSLDTO dto, final UserBean user) {

        final WeixiuSL model =
                this.weixiuSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(dto.getWorkOrderNum());

        // 修改维修状态
        dto.getDetails().forEach(l -> {
            model.getDetails().forEach(s -> {
                if (l.getId().toString().equals(s.getId().toString())) {
                    s.setStatus(l.getStatus());
                }
            });
        });

        this.weixiuItemSLRepository.saveAll(model.getDetails());
        // 更新资产状态为待维修
        final List<String> codes =
                dto.getDetails().stream().map(l -> l.getCode()).distinct().collect(Collectors.toList());

        if ((codes != null) && (codes.size() > 0)) {
            final List<Asset> assets = this.assetRepository.findByCodeIn(codes);
            if (null != assets) {
                assets.forEach(l -> {
                    l.setStatus(DCAMConsts.ASSET_STATUS_UNMAINTENANCE);
                });
                this.assetRepository.saveAll(assets);
            }
        }

        // 完成流程
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        this.confirmSLService.create(ConfirmSLDTO.builder().workOrderNum(dto.getWorkOrderNum()).taskId(dto.getTaskId())
                .createUser(user.getUsername()).createUserName(user.getName()).mainId(model.getId()).build());

    }

    @Override
    public WeixiuSLDTO confirmDetails(final String workOrderNum, final String taskId, final UserBean user) {

        WeixiuSL model = null;
        Long mainId = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {

                mainId = this.confirmSLService.getMainId(workOrderNum, taskId);
                if (mainId == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        model =
                                this.weixiuSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
                    } else {
                        mainId = this.confirmSLService.getMainId(workOrderNum, lastTaskId);
                        model = this.weixiuSLRepository.getOne(mainId);
                    }
                } else {
                    model = this.weixiuSLRepository.getOne(mainId);
                }
            } else if ("NULL".equals(taskId)) {
                model = this.weixiuSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.weixiuSLConverter.toDTO(model);
    }

    @Override
    public void confirmResultCreate(final WeixiuSLDTO dto, final UserBean user) {
        final WeixiuSL model =
                this.weixiuSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(dto.getWorkOrderNum());

        // 修改维修结果
        dto.getDetails().forEach(l -> {
            model.getDetails().forEach(s -> {
                if (l.getId().toString().equals(s.getId().toString())) {
                    s.setResult(l.getResult());
                }
            });
        });

        this.weixiuItemSLRepository.saveAll(model.getDetails());

        // 解锁资产恢复资产信息为在用
        this.weixiuSLCompleteUpdate(
                dto.getDetails().stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                dto.getWorkOrderNum());

        // 完成流程
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

    }

    @Override
    public WeixiuSLDTO confirmResultDetails(final String workOrderNum, final String taskId, final UserBean user) {
        final WeixiuSL model = this.weixiuSLRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
        return this.weixiuSLConverter.toDTO(model);
    }

    private void weixiuSLCompleteUpdate(final List<String> codes, final String workNum) {
        final List<AssetLifeCycleDTO> lifeList = new ArrayList<>();
        if ((codes != null) && (codes.size() > 0)) {
            final List<Asset> assets = this.assetRepository.findByCodeIn(codes);
            if (null != assets) {
                assets.forEach(l -> {
                    l.setLocked(false);
                    l.setStatus(DCAMConsts.ASSET_STATUS_USED);

                    // 生命周期
                    lifeList.add(AssetLifeCycleDTO.builder().code(l.getCode())
                            .lifeCycle(DCAMConsts.ASSET_LIFE_TYPE_WEIXIU)
                            .content(l.getName() + "已维修").workNum(workNum).build());

                });
                this.assetRepository.saveAll(assets);

                if (lifeList.size() > 0) {
                    this.assetLifeCycleService.batchCreate(lifeList);
                }
            }
        }
    }
}
